<?php
session_start();
include("load-settings.php");

if(!isset($_SESSION['user']))
	header("Location: login.php");

$user = $_SESSION['user'];

$result = mysql_query("SELECT * FROM user WHERE id = $user");
$row = mysql_fetch_array($result);
$type = $row['type'];

if(!isset($_GET['id']))
{
	header("Location: home.php");
}

$id = mysql_real_escape_string($_GET['id']);

$result = mysql_query("SELECT * FROM ticket WHERE id = $id");
$row = mysql_fetch_array($result);
$summary = $row['summary'];
$order = $row['order_record'];

if($row['status'] == 0)
	$status = "Pending";
else
	$status = "Resolved";

if($row['user'] != $user && $type != 2)
	header("Location: home.php");

$customer = $row['user'];
 $booster = '';

?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Veteran Boosters Order Tracking</title>
		<meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<link rel="stylesheet" href="css/bootstrap.min.css" />
		<link rel="stylesheet" href="css/font-awesome.css" />
		<link rel="stylesheet" href="css/fullcalendar.css" />
		<link rel="stylesheet" href="css/jquery.jscrollpane.css" />	
		<link rel="stylesheet" href="css/unicorn.css" />
		<!--[if lt IE 9]>
		<script type="text/javascript" src="js/respond.min.js"></script>
		<![endif]-->
		<link href="stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
		<script src="javascripts/application.js" type="text/javascript"></script>
	</head>	

<?php
	include("top.php");
?>

  <div class="container-fluid">
    <div class="row" style="margin-left: 15px">

      <!-- Breadcrumb line -->

      <div id="breadcrumb">
					<a href="#" title="Go to Home" class="tip-bottom"><i class="fa fa-home"></i> Home</a>
					<a href="#" class="current">Ticket</a>
		</div>
    </div>
  

    <div class="row-fluid">

	<div class="alert alert-info" style="margin-left: 15px">
   <?php
		echo "Summary: ".$summary."<br />";
		echo "Order: ".$order."<br />";
		echo "Status: ".$status."<br />";
   ?>
</div>
<?php
	if($status == "Resolved")
	{
?>
<div style = "margin-bottom: 20px;margin-left: 15px"><a href="unresolve-ticket.php?id=<?php echo $id; ?>" class="btn btn-success btn-xs">Reopen ticket</a></div>
<?php
	}
	else
	{
		?>
<div style = "margin-bottom: 20px;margin-left: 15px"><a href="resolve-ticket.php?id=<?php echo $id; ?>" class="btn btn-success btn-xs">Mark as resolved</a></div>
<?php
	}
		?>
  </div>
  
  <div class="row-fluid">
   <div class="col-lg-12">
      <div class="box support">
         <div class="box-header">
            <div class="title">Ticket Chat</div>
         </div>

         <div class="box-content">
            
            <ul class="chat-box" id="refresh">
               <div id="chat-messages-inner">
			   <?php
					$result = mysql_query("SELECT * FROM ticket_chat WHERE ticket = $id ORDER BY timestamp DESC");

					$messages = array();

					while($row = mysql_fetch_array($result))
					{
						$subresult = mysql_query("SELECT * FROM user WHERE id = ".$row['user']);
						$subrow = mysql_fetch_array($subresult);

						$row['name'] = $subrow['username'];
						$row['email'] = $subrow['paypal'];
						$row['type'] = $subrow['type'];

						array_push($messages, $row);
					}

					$x = 0;

					while(isset($messages[$x]))
					{
						if($messages[$x]['type'] == 0)
						{
							echo '<li class="arrow-box-right gray" id="msg-'.$messages[$x]['id'].'">';
							echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
							echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-gray">customer</span>';

							if($type == 2)
								echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_ticket_chat(".$messages[$x]['id'].")'>Remove</span>";

							echo '</span>';
							echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
							echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
							echo '<li class="divider"></li>';
						}
						else if($messages[$x]['type'] == 1)
						{
							echo '<li class="arrow-box-left gray" id="msg-'.$messages[$x]['id'].'">';
							echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
							echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-blue">booster</span>';

							if($type == 2)
								echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_ticket_chat(".$messages[$x]['id'].")'>Remove</span>";

							echo '</span>';
							echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
							echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
							echo '<li class="divider"></li>';
						}
						else if($messages[$x]['type'] == 2)
						{
							echo '<li class="arrow-box-left gray" id="msg-'.$messages[$x]['id'].'">';
							echo '<div class="avatar"><img class="avatar-small" src="images/avatars/'.$messages[$x]['type'].'.png"></div>';
							echo '<div class="info"><span class="name"><strong>'.$messages[$x]['name'].'</strong>';
                            echo '<span class="badge badge-red">administrator</span>';

							if($type == 2)
								echo "<span class='badge badge-red' style = 'margin-left: 5px; cursor: pointer;' onclick = 'delete_ticket_chat(".$messages[$x]['id'].")'>Remove</span>";

							echo '</span>';
							echo '<span class="time">'.date("d M Y g:i:sA", $messages[$x]['timestamp']).'</span>';
							echo '</div>'.stripslashes($messages[$x]['message']).'</li>';
							echo '<li class="divider"></li>';
						}

						$x++;
					}
				?>
         
</div>
            </ul>
         </div>

         <div class="box-footer flat padded" style = "height: 56px">
		 <?php
			if($user == $customer || $booster == $username || $type == 2)
			{
				echo '
            <div class="input-append">
			   <input type="hidden" id = "ticket" value = "'.$id.'" />
               <input type="text" name="msg-box" id="msg-box" onkeyup = "check_chat_send(event)">
               <ul class="add-on" style = "<!--margin-top: 35px; margin-right: -6px-->">
                  <li>
                     <button class="btn btn-success btn-xs" type="submit" onclick = "chat_send()">Send</button>
                  </li>
               </ul>
            </div>';
			}
			?>
         </div>
      </div>
   </div>
</div>

    <script>
        function check_chat_send (event)
        {
            if(event.keyCode == 13)
            {
                if(document.getElementById("msg-box").value != "")
                {
                    chat_send();
                }
            }
        }
        function chat_send ()
        {
            if(document.getElementById("msg-box").value != "")
            {
                var ajaxHandler = new XMLHttpRequest();

                ajaxHandler.onreadystatechange = function ()
                {
                    if(ajaxHandler.readyState == 4)
                    {
                        update_ticket_chat();
                        document.getElementById("msg-box").value = "";
                    }
                }

                var form = new FormData();
                form.append("msg-box", document.getElementById("msg-box").value);
                form.append("ticket", document.getElementById("ticket").value);

                ajaxHandler.open("POST", "ticket-reply.php");
                ajaxHandler.send(form);
            }
        }
        function delete_ticket_chat (id)
        {
            var ajaxHandler = new XMLHttpRequest();

            var form = new FormData();
            form.append("id", id);

            ajaxHandler.open("POST", "delete_ticket_chat.php");
            ajaxHandler.send(form);

            var target = document.getElementById("msg-"+id);
            target.parentNode.removeChild(target);
        }
        function update_ticket_chat ()
        {
            var ajaxHandler = new XMLHttpRequest();

            ajaxHandler.onreadystatechange = function ()
            {
                if(ajaxHandler.readyState == 4)
                {
                    var chat_box = document.getElementById("chat-messages-inner");

                    var messages = eval( '(' + ajaxHandler.responseText + ')' );

                    var i = 0;

                    chat_box.innerHTML = "";
                    var html_buffer = "";

                    while(messages[i] != null)
                    {
                        if(messages[i]['type'] != 0)
                        {
                            html_buffer += '<li class="arrow-box-left gray" id="msg-'+messages[i]['id']+'">';
                            html_buffer += '<div class="avatar"><img class="avatar-small" src="images/avatars/'+messages[i]['type']+'.png"></div>';
                            html_buffer += '<div class="info"><span class="name"><strong>'+messages[i]['name']+'</strong>';

                            if(messages[i]['type'] == 1)
                                html_buffer += '<span class="badge badge-blue">booster</span>';
                            else
                                html_buffer += '<span class="badge badge-red">administrator</span>';

                            <?php
                                if($type == 2)
                                    echo "html_buffer += '<span class=\"badge badge-red\" style = \"margin-left: 5px; cursor: pointer;\" onclick = \"delete_ticket_chat('+messages[i]['id']+')\">Remove</span>';";
                            ?>

                            html_buffer += '</span><span class="time">'+messages[i]['time']+'</span></div>';
                            html_buffer += messages[i]['message'];
                            html_buffer += '</li><li class="divider"></li>';
                        }
                        else
                        {
                            html_buffer += '<li class="arrow-box-right gray" id="msg-'+messages[i]['id']+'">';
                            html_buffer += '<div class="avatar"><img class="avatar-small" src="images/avatars/'+messages[i]['type']+'.png"></div>';
                            html_buffer += '<div class="info"><span class="name"><strong>'+messages[i]['name']+'</strong>';
                            html_buffer += '<span class="badge badge-gray">customer</span>';
                            <?php
                                if($type == 2)
                                    echo "html_buffer += '<span class=\"badge badge-red\" style = \"margin-left: 5px; cursor: pointer;\" onclick = \"delete_ticket_chat('+messages[i]['id']+')\">Remove</span>';";
                            ?>
                            html_buffer += '</span><span class="time">'+messages[i]['time']+'</span></div>';
                            html_buffer += messages[i]['message'];
                            html_buffer += '</li><li class="divider"></li>';
                        }
                        i++;
                    }

                    chat_box.innerHTML = html_buffer;
                }
            }

            var form = new FormData();
            form.append("id", <?php echo $id; ?>);

            ajaxHandler.open("POST", "ticket-chat-refresh.php");
            ajaxHandler.send(form);
        }
        function updateTimer ()
        {
            update_ticket_chat();
            setTimeout(updateTimer, 10000);
        }
        window.onload = function ()
        {
            <?php
                if($type != 0)
                    echo 'updateTimer();';
            ?>
        }
    </script>
  </div>
    </div>
<?php
	include("bottom.php");
?>
